<template>
  <!--  账号登录-->
  <div class="login-container" v-if="!isRegister">
    <div class="login-box">
      <h2>账号登录</h2>
      <span class="notice-font" v-if="isNotice">账号或密码有误，请从新输入</span>
      <span class="notice-font">{{ userIsExistMsg2 }}</span>
      <form style="text-align: center;" @submit.prevent="login">
        <!--        登录账号-->
        <div class="form-group" style="margin-top: 0.3rem">
          <label for="username">
            <van-icon name="manager" size="1.1rem" color="#fff"/>
          </label>
          <input type="text" id="username" name="username" v-model.trim="username" required placeholder="请输入账号"
                 @blur="handleBlur">
        </div>
        <!--        登录密码-->
        <div class="form-group">
          <label for="password">
            <van-icon name="lock" size="1.1rem" color="#fff"/>
          </label>
          <input type="password" id="password" name="password" v-model.trim="password" required placeholder="请输入密码">
        </div>
        <!--        记住账号密码-->
        <div class="form-group2">
          <div class="div1">
            <input type="checkbox" id="checkbox" name="checkbox" v-model.trim="rememberMe">
            <label @click="rememberMe = rememberMe === true ? false : true">记住密码</label>
          </div>
          <!--          没有账号，注册账号-->
          <div class="div2">
            <a href="#" @click="isRegister = true">没有账号，立即注册</a>
          </div>
        </div>
        <!--        登录按钮-->
        <button type="submit" style="margin: 0 auto;">登录</button>
      </form>
    </div>
  </div>
  <!--  账号注册-->
  <div class="login-container" v-if="isRegister">
    <div class="login-box">
      <h2>注册账号</h2>
      <span v-if="true" class="notice-font">{{passwordsMatch}}</span>
      <span class="notice-font">{{ passwordValidationMessage }}</span>
      <span class="notice-font">{{ userIsExistMsg }}</span>
      <form style="text-align: center;" @submit.prevent="regedit">
        <!--        手机号-->
        <div class="form-group" style="margin-top: 0.3rem">
          <label for="phone">
            <van-icon name="phone" size="1.1rem" color="#fff"/>
          </label>
          <input type="text" id="phone" name="phone" v-model.trim="phone" required placeholder="请输入手机号"
                 @blur="handleBlur">
        </div>
        <!--        设置密码-->
        <div class="form-group">
          <label for="setPassword">
            <van-icon name="lock" size="1.1rem" color="#fff"/>
          </label>
          <input minlength="6" type="password" id="setPassword" v-model.trim="setPassword" required
                 placeholder="设置登录密码" @blur="handleBlur2(this.setPassword.length)">
        </div>
        <!--        设置确认密码-->
        <div class="form-group">
          <label for="setPassword2">
            <van-icon name="lock" size="1.1rem" color="#fff"/>
          </label>
          <input minlength="6" type="password" id="setPassword2" v-model.trim="setPassword2" required
                 placeholder="确认登录密码" @blur="handleBlur2(this.setPassword2.length)">
          <!--          账号已注册，登录账号-->
          <!--                    <div class="div2">
                                <a href="#" @click="isLogin = true">已有账号，去登录</a>
                              </div>-->
          <!-- 当密码不匹配时显示错误消息 -->
        </div>
        <div class="form-group2" style="justify-content: right">
          <!--                  <div class="div1">
                              <input type="checkbox" id="checkbox" name="checkbox" required>
                              <span>记住密码</span>
                            </div>-->
          <div class="div3">
            <a href="#" @click="isRegister = false">已有账号，去登录</a>
          </div>
        </div>
        <!--        注册按钮-->
        <button type="submit" style="margin: 0 auto;">注册</button>
      </form>
    </div>
  </div>
</template>

<script>
import {Dialog, Toast} from 'vant'
export default {
  name: "Login",
  data() {
    return {
      username: '',
      password: '',
      phone: '',
      setPassword: '',
      setPassword2: '',
      isNotice: false,
      isRegister: false,
      rememberMe: false,
      passwordsMatch: '',
      userIsExistMsg: '',
      userIsExistMsg2: '',
      passwordValidationMessage: ''
    }
  },
  inject: ['$apiUrl', '$headImgUrl'],
  methods: {
    // 登录 ---验证登录信息
    async login() {
      // todo 这里需要发送请求判断密码是否正确
      const registerDTO = {
        phone: this.username,
        password: this.password
      }
      const url = this.$apiUrl + '/user/login';
      const {data: res} = await this.$http.post(url, registerDTO);
      console.log(res)
      if (res.message === '您输入的密码有误' || res.message === '该用户不存在') {
        this.isNotice = true
      } else if (res.message === '密码正确') {
        this.isNotice = false
        // 存储token和过期时间
        const expiresAt = JSON.stringify(Date.now() + 3 * 24 * 60 * 60 * 1000)
        this.phone = this.username
        const newUUID = uuidv4();
        localStorage.setItem('user_id', res.data.user_id)
        localStorage.setItem('token', newUUID)
        localStorage.setItem('expiresAt', expiresAt)
        localStorage.setItem('phone', this.username)
        localStorage.setItem('user_name', res.data.username)
        this.updateUUIDByPhone(this.phone, newUUID)
        // Redirect to home page
      }
    },
    // 注册 验证注册信息
    async regedit(event) {
      // 判断两个密码匹配
     this.commonMsg()

      if (this.passwordsMatch !== '' && this.userIsExistMsg !== '') { // 如果密码不匹配 或者用户已经存在
        event.preventDefault(); // 阻止表单提交
      } else {
        // todo 此处需要发送请求 将注册信息存入数据库
        const userId = uuidv4();
        const registerDTO = {
          phone: this.phone,
          password: this.setPassword,
          password2: this.setPassword2,
          userId: userId
        }
        const url = this.$apiUrl + '/user/add';
        const {data: res} = await this.$http.post(url, registerDTO)
        Dialog.alert({
          message: '注册成功，立即登录',
          theme: 'round-button',
        }).then(() => {
          // on close
          this.isRegister = false
        });
      }
    },
    // 当输入框失去焦点时 根据手机号查询用户是否存在
    handleBlur() {
      // 发请求前先验证手机号格式是否正确
      if (!this.isRegister) {
        if (!/^1[3456789]\d{9}$/.test(this.username)) {
          this.userIsExistMsg2 = "您输入的手机号格式有误";
          return
        } else {
          this.userIsExistMsg2 = '';
        }
      } else {
        if (!/^1[3456789]\d{9}$/.test(this.phone)) {
          this.userIsExistMsg = "您输入的手机号格式有误";
          return;
        } else {
          this.userIsExistMsg = '';
        }
      }
      // console.log("发送请求")
      const registerDTO = {
        phone: this.phone,
      }
      if (!this.isRegister) {
        registerDTO.phone = this.username
      }
      const url = this.$apiUrl + '/user/getUserByPhone';
      this.$http.post(url, registerDTO).then(res => {
        // console.log(res.data.data === null)
        // console.log(res.data)
        if (!(res.data.data === null)) {
          this.userIsExistMsg = "该用户已存在";
          this.userIsExistMsg2 = '';
        } else {
          this.userIsExistMsg = '';
          this.userIsExistMsg2 = '该用户不存在,可免费注册';
        }
      })
    },
    commonMsg(){
      console.log("判断密码是否匹配")
      if (this.setPassword === this.setPassword2) {
        return this.passwordsMatch = ''
      } else {
        return this.passwordsMatch = '两次输入的密码不匹配'
      }
    },
    handleBlur2(val) {
      this.passwordValidationMessage = ''
      if (val < 6) {
        this.passwordValidationMessage = '密码长度不能少于6位'
      }
    },
    // 根据手机号更新用户uuid
    updateUUIDByPhone(phone,uuid){
      const registerDTO = {
        phone: phone,
        uuid:uuid
      }
      const url = this.$apiUrl + '/user/updateUUIDByPhone';
        Toast.loading({
          message: '登录中...',
          duration: 0, // 持续展示 toast
          forbidClick: true,
        });
      this.$http.post(url, registerDTO).then(res => {
        this.phone = res.data.data.mobile;
        this.$router.push('/')
      }).finally(() =>{
        Toast.clear();
      })
    }
  },

watch: {
  rememberMe(newValue)
  {
    if (newValue) {
      localStorage.setItem('username', this.username);
      localStorage.setItem('password', this.password);
    } else {
      localStorage.removeItem('username');
      localStorage.removeItem('password');
    }
  },
  // 判断两个密码匹配
  setPassword2(newValue,oldValue){
    console.log(newValue,oldValue)
    this.commonMsg()
  }
}
,
mounted()
{
  const username = localStorage.getItem('username');
  const password = localStorage.getItem('password');
  if (username && password) {
    this.username = username;
    this.password = password;
    this.rememberMe = true;
  }
}
,
computed: {
  // 计算属性，用于检查两个密码是否匹配
  passwordsMatch() {
  }
}
}
</script>

<style scoped>
.login-container {
  width: 100vw;
  height: 100vh;
  box-sizing: border-box;
  background-image: url("/src/assets/images/bj.jpg");
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  opacity: 0.9;
}

.notice-font {
  display: block;
  margin-left: 2rem;
  color: red;
  font-size: 14px;
  font-weight: 600;
}

.login-container .login-box {
  position: fixed;
  top: 60%;
  left: 50%;
  /*width: 15rem;*/
  /*height: 11rem;*/
  transform: translate(-50%, -50%);
  background-color: rgba(0, 0, 0, 0.25) !important;
  /* 半透明黑色背景 */
  padding: 1rem 1.5rem 1rem 1.5rem;
  border-radius: 0.6rem;
  box-shadow: 0 0 10.8rem 0.2rem rgba(0, 0, 0, 0.15);
}

.login-box h2 {
  margin: 0 0 0 2rem;
  font-size: 1.15rem;
  font-weight: normal;
  font-stretch: normal;
  letter-spacing: 0.1rem;
  color: #ffffff;
}

.form-group {
  margin: 1rem 0;
  display: flex;
  justify-content: space-between;
}

.form-group label {
  line-height: 2rem;
  font-weight: bold;
}

.form-group input {
  padding: 0.35rem 0.4rem;
  border-radius: 0.1rem;
  /*background-color: #b5c2d6;*/
  border: none;
  font-size: 16px;
  margin: 0 0.4rem 0 1rem;
  background-color: rgba(181, 194, 214, 0.9) !important;
}

.form-group2 {
  display: flex;
  /*line-height: 2rem;*/
  justify-content: space-between;
  font-weight: bold;
  font-size: 12px;
  margin: -0.5rem 0.6rem 0.5rem 1.8rem;
}

.form-group2 .div1 {
  /*flex: 1;*/
  display: flex;
  align-items: center;
}

.form-group2 .div1 span {
  vertical-align: middle;
  margin-bottom: 0.1rem;
}

.form-group2 .div2 a,
.form-group2 .div3 a {
  color: #3498db;
  font-size: 0.6rem;
}

.form-group2 .div2 a:visited,
.form-group2 .div3 a:visited {
  color: purple; /* 已访问链接的颜色 */
}

button[type="submit"] {
  width: 8.5rem;
  height: 2rem;
  line-height: 2rem;
  background-color: #3498db;
  color: white;
  border: none;
  border-radius: 0.3rem;
  margin-top: 0.8rem;
  cursor: pointer;
}
</style>
